package com.kc.statistics.controller;

import com.alibaba.fastjson.JSON;
import com.kc.statistics.bean.Statistics;
import com.kc.statistics.bean.TrackEvent;
import com.kc.statistics.dao.StatisticsDao;
import com.kc.statistics.httpmodel.MobileVO;
import com.kc.statistics.httpmodel.StatisticsParms;
import com.kc.statistics.utils.*;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Controller
public class StatisticsController {
    private static final Logger log = LoggerFactory.getLogger(StatisticsController.class);


    @Autowired
    private StatisticsDao statisticsDao;

    @PostMapping("/track/hm.gif")
    public void track(HttpServletRequest request, HttpServletResponse response, String data) {

        try {
            // 解决跨域
            request.setCharacterEncoding("UTF-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
            response.setContentType("image/jpeg");

            if (StringUtils.isNotBlank(data)) {
                /**
                 *  对data=xxx，进行解码，先改处理%25的问题 URLDecoder.decode
                 */

                data = data.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                data = URLDecoder.decode(data, "UTF-8");
                data = URLDecoder.decode(data, "UTF-8");

                // base64解码
                byte[] encodeBase64 = Base64.decodeBase64(data.getBytes("utf-8"));
                String strdata = new String(encodeBase64, "UTF-8");

                List<MobileVO> MobileVOs = JSON.parseArray(strdata, MobileVO.class);
                //保存数据后面修改，直接存库效率较低
                for (MobileVO mobileVO : MobileVOs) {
                    statisticsDao.saveMobileVo(mobileVO);
                }

            }

            //返回gif
            ServletOutputStream os = response.getOutputStream();
            BufferedImage im = ImageUtils.generateImageIo();
            ImageIO.write(im, "gif", os);
            os.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping(value = {"/hm.gif"})
    public void hm(HttpServletRequest request, HttpServletResponse response, StatisticsParms p, TrackEvent trackEvent) {
        try {
            // 解决跨域
            request.setCharacterEncoding("UTF-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
            response.setContentType("image/jpeg");

            // 获取HTTP IP
            if (null != p || null != trackEvent) {
                String ipAddr = IpUtils.getIpAddr(request);

                // 解码设置实体的值
                p.setTt(DecodeUtils.decode(p.getTt()));
                p.setSu(DecodeUtils.decode(DecodeUtils.decode(p.getSu())));
                p.setNu(DecodeUtils.decode(DecodeUtils.decode(p.getNu())));

                Statistics st = new Statistics();
                BeanUtils.copyProperties(st, p);
                st.setIp(ipAddr);

                st.setAt(DateUtils.getDateMs());// 时间

                /**
                 * 利用QQ IP纯正库解析IP 地址所属地区，
                 */
                if (StringUtils.isNotBlank(st.getIp())) {
                    String regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
                    Pattern pp = Pattern.compile(regex);
                    Matcher m = pp.matcher(st.getIp());
                    if (m.find()) {
                        String area = "";
                        String country = "";
                        try {
                            area = "";//地区
                            country = "";// 国家
                            area = AreaUtils.findArea(area);
                            if (StringUtils.isNotBlank(area)) {
                                st.setAr(area);
                            }
                            if (StringUtils.isNotBlank(country)) {
                                st.setNetopt(country);
                            }
                        } catch (Exception e) {
                        }
                    }

                }

                // 浏览器识别，操作系统，设备类型
                if (!StringUtils.isBlank(st.getUa())) {
                    UserAgent userAgent = UserAgent.parseUserAgentString(st.getUa());
                    Browser browser = userAgent.getBrowser();
                    OperatingSystem os = userAgent.getOperatingSystem();
                    st.setBrowser(browser.getName());
                    st.setOs(os.getName());
                    st.setDevicetype(os.getDeviceType().getName());
                }

                /**
                 * 如果是事件
                 */
                if ((StringUtils.isNotBlank(trackEvent.getTag())) && (trackEvent.getTag().equals("_trackEvent"))) {
                    String ct = trackEvent.getCt();
                    ct = DecodeUtils.decode(ct);
                    String at = trackEvent.getAt();
                    at = DecodeUtils.decode(at);
                    String kl = trackEvent.getKl();
                    kl = DecodeUtils.decode(kl);
                    String vl = trackEvent.getVl();
                    vl = DecodeUtils.decode(vl);
                    trackEvent.setCt(ct);
                    trackEvent.setAt(at);
                    trackEvent.setKl(kl);
                    trackEvent.setVl(vl);
                    //保存到 自定议事件表中
                    statisticsDao.savetrackEvent(trackEvent, st);
                } else {
                    // 保存到自动流量中
                    statisticsDao.saveStatistics(st);
                }
            }
            //返回一张1px的gif图片  CODE=200
            ServletOutputStream os = response.getOutputStream();
            BufferedImage im = ImageUtils.generateImageIo();
            ImageIO.write(im, "gif", os);
            os.close();
        } catch (Exception e) {
        }
    }
}